import threading
import time
import ctypes
import inspect


class X(threading.Thread):
    def run(self):
        while True:
            time.sleep(1)
            print("子线程！1")
            time.sleep(1)
            print("子线程！2")
            time.sleep(1)
            print("子线程！3")
            time.sleep(1)
            print("子线程！4")
            time.sleep(1)
            print("子线程！5")




def async_raise(thread_id, exctype):
    """
    通过C语言的库抛出异常
    :param thread_id:
    :param exctype:
    :return:
    """
    # 在子线程内部抛出一个异常结束线程
    thread_id = ctypes.c_long(thread_id)
    if not inspect.isclass(exctype):
        exctype = type(exctype)
    res = ctypes.pythonapi.PyThreadState_SetAsyncExc(thread_id, ctypes.py_object(exctype))
    if res == 0:
        raise ValueError("线程id违法")
    elif res != 1:
        ctypes.pythonapi.PyThreadState_SetAsyncExc(thread_id, None)
        raise SystemError("异常抛出失败")


def stop_thread_now(thread):
    # 结束线程
    async_raise(thread.ident, SystemExit)


if __name__ == "__main__":
    # 可以在子线程任何时候随时结束子线程
    x = X()
    x.start()
    print(x.is_alive())
    time.sleep(7)
    stop_thread_now(x)
    time.sleep(1)
    print(x.is_alive())